package com.wangxiaobao.charge.mylibrary.request;

import java.nio.ByteBuffer;
import java.util.Arrays;

public class RequestData {
    public static final int OP_HEAD_GET = 0xEF;
    public static final int OP_HEAD_SET = 0xEE;
    private final int opHead;
    private final int ctl;
    private final int EXCEPT_LEN = 0x20;
    private final int reserved;
    private final int dataLength;
    private byte[] data;
    private RequestData(int opHead, int reserved,int ctl, byte[] payload) {
        this.opHead = opHead;
        this.reserved = reserved;
        this.ctl = ctl;
        this.dataLength = payload == null ? 0 : payload.length;
        if (dataLength > 0) {
            this.data = Arrays.copyOf(payload, dataLength);
        }
    }

    public int getOpHead() {
        return opHead;
    }

    public int getCtl() {
        return ctl;
    }


    public byte[] getByteData() {
        // h  1   1  c   1  d
        // ef 00 00 01 20 00
        // h  1  c  l  1  d
        // ee 00 01 04 20 7b 47 8c 62

        int capacity=5+dataLength;
        ByteBuffer buffer=ByteBuffer.allocate(capacity);
        buffer.put((byte) opHead);
        if(opHead == OP_HEAD_GET){
            buffer.put((byte) 0x00);
            buffer.put((byte) 0x00);
        }else{
            buffer.put((byte) reserved);
        }
        buffer.put((byte) ctl);
        if(opHead == OP_HEAD_SET){
            buffer.put((byte) dataLength);
        }
        buffer.put((byte) EXCEPT_LEN);
        buffer.put(data);
        return buffer.array();
    }

    public static class Builder{
        private int opHead;
        private int reserved;
        private int ctl;
        private byte[] payload;

        public Builder opHead(int opHead) {
            this.opHead = opHead;
            return this;
        }
        public Builder reserved(int reserved) {
            this.reserved = reserved;
            return this;
        }
        public Builder ctl(int ctl) {
            this.ctl = ctl;
            return this;
        }

        public Builder payload(byte[] payload) {
            this.payload = payload;
            return this;
        }
        public RequestData build() {
            return new RequestData(opHead,reserved,ctl,payload);
        }
    }

}
